﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Http;
using System.Web.Http.Dispatcher;
using System.Web.Http.ModelBinding;
using Web.HttpParameterBindings;
using Newtonsoft.Json.Linq;
using System.Collections.Specialized;

namespace Web
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config) {
            config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config));
            var suffix = typeof(DefaultHttpControllerSelector).GetField("ControllerSuffix",
                                                                         BindingFlags.Static | BindingFlags.Public);
            if (suffix != null) suffix.SetValue(null, "ApiController");

            config.Filters.Add(new AuthorizeAttribute());
            config.Filters.Add(new WebApiExceptionFilter());

            config.ParameterBindingRules.Insert(0, param => {
                if (param.ParameterType == typeof(JObject)) {
                    return new JObjectWrapperParameterBinding(param);
                } else if (param.ParameterType == typeof(ReqWrapperQuery)) {
                    return new ParamBindingForQueryReqWrapper(param);
                } else if (param.ParameterType == typeof(ReqWrapperInsert)) {
                    return new InsertReqWrapperParamBinding(param);
                } else if (param.ParameterType == typeof(ReqWrapperUpdate)) {
                    return new UpdateReqWrapperParamBinding(param);
                } else if (param.ParameterType == typeof(ReqWrapperMasterDetailInsert)) {
                    return new ParamBindingForMasterDetailInsert(param);
                } else if (param.ParameterType == typeof(ReqWrapperMasterDetailUpdate)) {
                    return new ParamBindingForMasterDetailUpdate(param);
                }

                return null;
            });


            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}
